package com.jinwei.qunguanjia.system.service;

import com.jinwei.qunguanjia.system.dto.SysLoginUser;
import com.jinwei.qunguanjia.system.dto.SysUserDTO;
import com.jinwei.qunguanjia.system.exception.UserServiceException;
import com.jinwei.qunguanjia.common.enums.UserStatusEnum;
import com.jinwei.qunguanjia.common.exception.GlobalExceptionHelper;
import com.jinwei.qunguanjia.common.utils.JsonUtils;
import com.jinwei.qunguanjia.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 用户验证处理
 *
 * @author ruoyi
 */
@Slf4j
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Resource
    private SysUserService sysUserService;

    @Resource
    private SysPermissionService sysPermissionService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException
    {
        SysUserDTO user = sysUserService.getUserByUserName(username);
        if (StringUtils.isNull(user)) {
            log.info("登录用户：{} 不存在.", username);
            throw GlobalExceptionHelper.localServiceException(UserServiceException.USER_PASSWORD_NOT_MATCH);
        }else if (UserStatusEnum.DISABLE.getCode().equals(user.getUserStatus())) {
            log.info("登录用户：{} 已被停用.", username);
            throw GlobalExceptionHelper.localServiceException(UserServiceException.USER_DISABLE, username);
        }
        return createLoginUser(user);
    }

    private UserDetails createLoginUser(SysUserDTO user)
    {
        return new SysLoginUser(user.getUserId(), user.getUserName(), user.getDeptId(), user.getUserPassword(), JsonUtils.toJsonString(user), sysPermissionService.listMenuPermission(user.getUserId()));
    }
}
